﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Reflection;

namespace QL_Truong_Hoc
{
    public partial class frmQuanLyNguoiDung : DevExpress.XtraEditors.XtraForm
    {
        private const string mcstrRoleCode = "them_nguoi_dung";
        private clsEnum.FORM_MODE memMode;

        private int mintNextID = -1;

        public frmQuanLyNguoiDung()
        {
            InitializeComponent();
        }

        private void frmQuanLyNguoiDung_Load(object sender, EventArgs e)
        {
            if (!clsCommon.fncCheckRole(Program.glstRoles, mcstrRoleCode))
            {
                this.BeginInvoke(new MethodInvoker(this.Close));
                return;
            }

            // TODO: This line of code loads data into the 'qLTHDataSet.tNhomQuyen' table. You can move, or remove it, as needed.
            this.tNhomQuyenTableAdapter.Fill(this.qLTHDataSet.tNhomQuyen);
            // TODO: This line of code loads data into the 'qLTHDataSet.tblUser' table. You can move, or remove it, as needed.
            this.tblUserTableAdapter.Fill(this.qLTHDataSet.tblUser);

            //DataTable objQuyen = new DataTable();
            //objQuyen.Columns.Add("Quyen_TEN");
            //objQuyen.Columns.Add("Quyen_ID");

            //objQuyen.Rows.Add("Admin", (int)clsEnum.NHOM_QUYEN.ADMIN);
            //objQuyen.Rows.Add("Nhập liệu", (int)clsEnum.NHOM_QUYEN.NHAP_LIEU);
            //objQuyen.Rows.Add("Báo cáo", (int)clsEnum.NHOM_QUYEN.BAO_CAO);

            //cbGridQuyenNguoiDung.DataSource = objQuyen;
            //cbNhomQuyen.Properties.DataSource = objQuyen;

            this.memMode = clsEnum.FORM_MODE.VIEW;
            xSetFormMode(this.memMode);

            Program.gevnApplication.evnRoleUpdated += new clsEvents.dgaRoleUpdated(gevnApplication_evnRoleUpdated);
        }

        void gevnApplication_evnRoleUpdated()
        {
            try
            {
                // TODO: This line of code loads data into the 'qLTHDataSet.tNhomQuyen' table. You can move, or remove it, as needed.
                this.tNhomQuyenTableAdapter.Fill(this.qLTHDataSet.tNhomQuyen);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private bool xSetFormMode(clsEnum.FORM_MODE emMode)
        {
            bool blnResult = false;
            try
            {
                this.memMode = emMode;

                switch (emMode)
                {
                    case clsEnum.FORM_MODE.VIEW:
                        mniSave.Enabled = false;
                        mniAdd.Enabled = true;
                        mniEdit.Enabled = true;
                        mniDelete.Enabled = false;
                        mniCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                        //clear combobox
                        txtFullName.Text = "";
                        txtPassword.Text = "";
                        txtPasswordConfirm.Text = "";
                        txtUser.Text = "";
                        cbNhomQuyen.SendKey(new KeyEventArgs(Keys.Control | Keys.Delete));

                        //disable để tránh bị sửa
                        txtUser.Enabled = false;
                        txtPasswordConfirm.Enabled = false;
                        txtPassword.Enabled = false;
                        txtFullName.Enabled = false;
                        cbNhomQuyen.Enabled = false;

                        break;

                    case clsEnum.FORM_MODE.ADD:
                        mniSave.Enabled = true;
                        mniAdd.Enabled = false;
                        mniEdit.Enabled = false;
                        mniDelete.Enabled = false;
                        mniCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                        //enable control
                        txtUser.Enabled = true;
                        txtPasswordConfirm.Enabled = true;
                        txtPassword.Enabled = true;
                        txtFullName.Enabled = true;
                        cbNhomQuyen.Enabled = true;

                        //clear combobox
                        txtFullName.Text = "";
                        txtPassword.Text = "";
                        txtPasswordConfirm.Text = "";
                        txtUser.Text = "";
                        cbNhomQuyen.SendKey(new KeyEventArgs(Keys.Control | Keys.Delete));

                        break;

                    case clsEnum.FORM_MODE.EDIT:
                        mniSave.Enabled = true;
                        mniAdd.Enabled = false;
                        mniEdit.Enabled = false;
                        mniDelete.Enabled = true;
                        mniCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                        //enable control
                        txtUser.Enabled = false;
                        txtPasswordConfirm.Enabled = true;
                        txtPassword.Enabled = true;
                        txtFullName.Enabled = true;
                        cbNhomQuyen.Enabled = true;

                        break;
                }

                return true;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
            return blnResult;
        }

        private void mniAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                xSetFormMode(clsEnum.FORM_MODE.ADD);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void mniEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                mintNextID = clsCommon.fncCnvNullToInt(dgvNguoiDung.GetFocusedRowCellValue(colUserID));

                if (mintNextID <= 0)
                {
                    clsCommon.fncMsgInfo("Hãy chọn một giá trị để sửa.");
                    dgvNguoiDung.Focus();
                    return;
                }

                xEdit(mintNextID);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private bool xEdit(int intID)
        {
            bool blnResult = false;
            try
            {
                //set form sang edit mode
                xSetFormMode(clsEnum.FORM_MODE.EDIT);

                //hiển thị dữ liệu
                xView(intID);
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
            }
            return blnResult;
        }

        private bool xView(int intID)
        {
            bool blnResult = false;
            try
            {
                //lấy dữ liệu
                DTO.TblUserDTO objUser = DAO.TblUserDAO.Select(Program.gobjDb, intID);

                //fill combobox
                txtFullName.Text = objUser.Fullname;
                txtUser.Text = objUser.Username;
                cbNhomQuyen.EditValue = objUser.RoleID;
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
            }
            return blnResult;
        }

        private void mniDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                string strUser = clsCommon.fncCnvNullToString(dgvNguoiDung.GetFocusedRowCellValue(colUsername));

                if (strUser == Program.gstrCurrentUser) return;

                if (!clsCommon.fncMsgConfirm("Bạn có chắc muốn xóa người dùng " + strUser + " ?")) return;

                DAO.TblUserDAO.Delete(Program.gobjDb, Program.gobjTrans, mintNextID);

                tblUserTableAdapter.Fill(this.qLTHDataSet.tblUser);

                dgvNguoiDung.FocusedRowHandle = 0;
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
            }
        }

        private void mniCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!clsCommon.fncMsgConfirm("Dữ liệu sẽ không được lưu. Bạn có chắc muốn hủy?")) return;

                //mKhungDaoTaoMonTableAdapter.GetData();
                tblUserTableAdapter.Fill(this.qLTHDataSet.tblUser);

                xSetFormMode(clsEnum.FORM_MODE.VIEW);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void mniSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                //check valid trước khi tiếp tục
                if (!validControlBlank.Validate()) return;
                if (!validPassword.Validate()) return;

                switch (this.memMode)
                {
                    case clsEnum.FORM_MODE.ADD:
                        if (xAddNew())
                        {
                            //this.mKhungDaoTao_getallbyHeDaoTaoTableAdapter.GetData((int)this.memTrinhDo);
                            tblUserTableAdapter.Fill(this.qLTHDataSet.tblUser);
                            xSetFormMode(clsEnum.FORM_MODE.VIEW);
                        }
                        break;

                    case clsEnum.FORM_MODE.EDIT:
                        if (xUpdate())
                        {
                            //this.mKhungDaoTao_getallbyHeDaoTaoTableAdapter.GetData((int)this.memTrinhDo);
                            tblUserTableAdapter.Fill(this.qLTHDataSet.tblUser);
                            xSetFormMode(clsEnum.FORM_MODE.VIEW);
                        }
                        break;
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private bool xAddNew()
        {
            bool blnResult = false;
            try
            {
                if (DAO.clsDbAccess.fncIsUserExist(txtUser.Text.Trim().ToLower()))
                {
                    clsCommon.fncMsgWarning("Tên đăng nhập đã tồn tại. Hãy chọn một tên khác.");
                    txtUser.Focus();
                    return false;
                }

                if (clsCommon.fncMsgConfirm("Dữ liệu sẽ được lưu. Bạn có chắc chắn?"))
                {
                    //thêm mới khung đào tạo
                    DTO.TblUserDTO objUser = new DTO.TblUserDTO();
                    objUser.Fullname = txtFullName.Text.Trim();
                    objUser.Username = txtUser.Text.Trim().ToLower();
                    objUser.Password = clsCommon.fncGetSHA1HashData(txtPassword.Text.Trim());
                    objUser.RoleID = clsCommon.fncCnvNullToInt(cbNhomQuyen.EditValue);

                    //insert db khung đào tạo
                    DAO.TblUserDAO.Insert(Program.gobjDb, Program.gobjTrans, objUser);

                    //insert db khung đào tạo + môn học
                    tblUserTableAdapter.Update(this.qLTHDataSet.tblUser);

                    return true;
                }
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
                clsCommon.fncMsgError("Lưu dữ liệu không thành công. Hãy kiểm tra dữ liệu và thử lại.");
            }
            return blnResult;
        }

        private bool xUpdate()
        {
            bool blnResult = false;
            try
            {
                if (clsCommon.fncMsgConfirm("Dữ liệu sẽ được lưu. Bạn có chắc chắn?"))
                {
                    //thêm mới khung đào tạo
                    DTO.TblUserDTO objUser = new DTO.TblUserDTO();
                    objUser.Fullname = txtFullName.Text.Trim();
                    objUser.Username = txtUser.Text.Trim().ToLower();
                    objUser.Password = clsCommon.fncGetSHA1HashData(txtPassword.Text.Trim());
                    objUser.RoleID = clsCommon.fncCnvNullToInt(cbNhomQuyen.EditValue);
                    objUser.UserID = mintNextID;

                    //insert db khung đào tạo
                    DAO.TblUserDAO.Update(Program.gobjDb, Program.gobjTrans, objUser);

                    //insert db khung đào tạo + môn học
                    tblUserTableAdapter.Update(this.qLTHDataSet.tblUser);

                    return true;
                }
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
                clsCommon.fncMsgError("Lưu dữ liệu không thành công. Hãy kiểm tra dữ liệu và thử lại.");
            }
            return blnResult;
        }

        private void grdControlNguoiDung_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                //chỉ kích hoạt ở trạng thái view
                if (this.memMode != clsEnum.FORM_MODE.VIEW) return;

                //chỉ kích hoạt với chuột trái
                if (e.Button != System.Windows.Forms.MouseButtons.Left) return;

                mintNextID = clsCommon.fncCnvNullToInt(dgvNguoiDung.GetFocusedRowCellValue(colUserID));

                if (mintNextID <= 0)
                { return; }

                xView(mintNextID);
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
            }
        }

        private void btnNhomQuyen_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                frmQuanLyNhomQuyen objForm = new frmQuanLyNhomQuyen();
                //check
                foreach (Form form in Application.OpenForms)
                {
                    if (form.GetType() == objForm.GetType())
                    {
                        form.Activate();
                        return;
                    }
                }

                objForm.MdiParent = this.MdiParent;
                objForm.Show();
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
            finally { Cursor.Current = Cursors.Default; }
        }
    }
}